package com.star.system.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.star.system.cache.SystemCache;
import com.star.system.service.CaptchaService;
import com.star.common.enums.BizStatus;
import com.star.common.exception.BizException;
import lombok.SneakyThrows;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author yangzj
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {
    @Resource
    private RedissonClient redisson;

    @SneakyThrows
    @Override
    public void create(String uuid, int width, int height, HttpServletResponse response) {
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(width, height, 4, 20);
            // 缓存验证码 10分钟
            redisson.getBucket(SystemCache.CAPTCHA + uuid).set(captcha.getCode(), 10, TimeUnit.MINUTES);
            response.setContentType("image/png");
            captcha.write(outputStream);
        }
    }

    @Override
    public void verify(String uuid, String captcha) {
        RBucket<String> bucket = redisson.getBucket(SystemCache.CAPTCHA + uuid);
        if (Objects.equals(captcha, bucket.get())) {
            bucket.delete();
        } else {
            throw new BizException(BizStatus.VERIFY_CAPTCHA);
        }
    }
}
